package com.iwe3.protal.service;

import cn.hutool.json.JSONUtil;
import com.iwe3.protal.entity.BookTypeEntity;
import com.iwe3.protal.mapper.BookTypeMapper;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.BoundListOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.stream.Collectors;


@Service
public class BookTypeServiceImpl implements IBookTypeService{

    private final BookTypeMapper bookTypeMapper;
    private final RedisTemplate redisTemplate;

    public BookTypeServiceImpl(BookTypeMapper bookTypeMapper, @Qualifier("redisTemplate") RedisTemplate redisTemplate) {
        this.bookTypeMapper = bookTypeMapper;
        this.redisTemplate = redisTemplate;
    }


    @Override
    public List<BookTypeEntity> findAll() {
        // 询问：Redis 是否存在 书籍类型数据
        BoundListOperations blp = redisTemplate.boundListOps("bookTypes");
        // 没有：查询数据库
        if(!redisTemplate.hasKey("bookTypes")){
            List<BookTypeEntity> all = bookTypeMapper.findAll();
            // 添加到redis中
            all.forEach( e-> blp.leftPush(e));
        }
        // 有：直接返回
        List<LinkedHashMap> list = blp.range(0, blp.size() - 1);
        return list.stream().map( e->{
            String s = JSONUtil.toJsonStr(e);
            return JSONUtil.toBean(s,BookTypeEntity.class);
        }).collect(Collectors.toList());
    }
}
